/**
 * Created by tanbingqin on 2019/11/22.
 */
import { messages } from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import AdvancedTable from 'components/advanced-table'
const { SimpleTable } = AdvancedTable;
import constants from 'share/constants';
import {
  Button, Popover, message, Col, Row, Dropdown,
  Icon, Menu, Table, Tabs, Badge, Popconfirm, Radio,
  Select, Divider
} from 'antd';
const Option = Select.Option;
import formUtil from 'containers/setting/form/form-util'
import formService from 'containers/setting/form/form.service';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute';
import Priority from 'components/template/priority'
import openSlideFrame from "share/openSlideFrame";
import Space from "components/space";

class FormListV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchForm: [
        {
          id: 'fromType',
          label: messages('request-2.key372')/*层级*/,
          colSpan: 8,
          component: <Radio.Group>
            <Radio value="ALL">{messages('common.all')/*全部*/}</Radio>
            <Radio value={1}>{messages('request-2.key373')/*公司*/}</Radio>
            <Radio value={2}>{messages('request-2.key374')/*帐套*/}</Radio>
            <Radio value={3}>{messages('request-2.key448')/*租户*/}</Radio>
          </Radio.Group>,
          initialValue: 'ALL',
          dataIndex: 'fromType',
          parser: value => ({
            fromType: value !== 'ALL' ? value : undefined
          }),
          tagParser: value => {
            if (value === 'ALL') {
              return messages('common.all')/*全部*/;
            } else {
              return value === 1 ? messages('request-2.key373')/*公司*/ : (value === 2 ? messages('request-2.key374')/*帐套*/ : messages('request-2.key448')/*租户*/);
            }
          }
        },
        {
          id: 'levelOrgId',
          dataIndex: 'organization',
          label: messages('request-2.key375')/*所属组织*/,
          colSpan: 8,
          parser: value => ({
            setOfBooksId: value && value.range === 'SET_OF_BOOK' ? value.rangeValue.setOfBooksId : undefined,
            companyId: value && value.range === 'COMPANY' ? value.rangeValue.id : undefined
          }),
          tagParser: value => {
            if (value && value.range === 'SET_OF_BOOK') {
              return value.rangeValue.setOfBooksName;
            }
            if (value && value.range === 'COMPANY') {
              return value.rangeValue.name;
            }
          },
          component: <Priority onlySetOfBooks />,
        },
        {
          id: 'companyOIDs',
          label: messages('request-2.key376')/*启用公司*/,
          colSpan: 8,
          component: 'Chooser',
          props: {
            labelKey: 'name',
            valueKey: 'id',
            type: 'priority_company'
          },
          dataIndex: 'customFormCompanyRequest',
          parser: value => ({
            searchAssignCompanyOIDs: value ? value.map(item => item.companyOID) : null
          })
        },
        {
          id: 'formName', label: messages('request-2.key26')/*表单名称*/, component: 'Input', dataIndex: 'formName',
          colSpan: 8,
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'formType', label: messages('request-2.key377')/*表单类型*/, dataIndex: 'formType',
          colSpan: 8,
          component: 'Selector',
          props: {
            type: 'formTypeList',
            params: { id: props.selectedItem && props.selectedItem.id ? props.selectedItem.id : undefined }
          }
        },
        {
          id: 'formCode', label: messages('request-2.key24')/*表单编码*/, component: 'Input', dataIndex: 'formCode',
          colSpan: 8,
          props: {
            placeholder: messages('common.please.input')/*请输入*/
          }
        },
        {
          id: 'valid',
          label: messages('common.column.status')/*状态*/,
          colSpan: 8,
          component: <Radio.Group>
            <Radio value="ALL">{messages('common.all')/*全部*/}</Radio>
            <Radio value="true">{messages('request-2.key378')/*启用temp*/}</Radio>
            <Radio value="false">{messages('request-2.key379')/*禁用temp*/}</Radio>
          </Radio.Group>,
          initialValue: 'ALL',
          dataIndex: 'valid',
          parser: value => ({
            valid: value !== 'ALL' ? value : undefined
          }),
          tagParser: value => {
            if (value === 'ALL') {
              return messages('common.all')/*全部*/;
            } else {
              return value === "true" ? messages('request-2.key378')/*启用temp*/ : messages('request-2.key379')/*禁用temp*/;
            }
          }
        },
      ],
      columns: [
        {
          title: messages('request-2.key28')/*顺序号*/,
          dataIndex: 'sequence',
          width: 80
        },
        {
          title: messages('request-2.key372')/*层级*/,
          dataIndex: 'fromType',
          render: (value, record) => {
            return value === 1 ? messages('request-2.key373')/*公司*/ : (value === 2 ? messages('request-2.key374')/*帐套*/ : messages('request-2.key448')/*租户*/)
          }
        },
        {
          title: messages('request-2.key375')/*所属组织*/,
          dataIndex: 'organization',
          render: (value, record) => {
            return record.fromType === 3 ? (<Popover placement="topLeft" content={record.tenantName}>{record.tenantName}</Popover>) : (record.fromType === 1 ?
              <Popover placement="topLeft" content={record.companyName}>{record.companyName}</Popover> :
              <Popover placement="topLeft" content={record.setOfBooksName}>{record.setOfBooksName}</Popover>)
          }
        },
        {
          title: messages('request-2.key376')/*启用公司*/,
          dataIndex: 'customFormCompanyRequest',
          render: (value, record) => {
            return (record.fromType === 2 || record.fromType === 3) ? <Popover placement="topLeft" content={formUtil.getCompanyName(value)}>{formUtil.getCompanyName(value)}</Popover> :
              <Popover placement="topLeft" content={record.companyName}>{record.companyName}</Popover>
          }
        },
        {
          title: messages('request-2.key26')/*表单名称*/,
          dataIndex: 'formName',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-2.key377')/*表单类型*/,
          dataIndex: 'formType',
          hide: true,
          render: value => value ? <Popover placement="topLeft" content={constants.getTextByValue(value, 'documentTypeForShow')}>
            {constants.getTextByValue(value, 'documentTypeForShow')}
          </Popover> : '-'
        },
        {
          title: messages('request-2.key24')/*表单编码*/,
          dataIndex: 'formCode',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('common.remark')/*备注*/,
          dataIndex: 'remark',
          width: '20%',
          hide: true,
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'valid',
          width: 80,
          render: valid =>
            <Badge
              status={valid ? 'success' : 'error'}
              text={valid ? messages('request-2.key378')/*启用temp*/ : messages('request-2.key379')/*禁用temp*/}
            />
        },
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'operate',
          width: 160,
          render: (value, record) => {
            return (
              <div>
                {!(record.referenceOID && [3001, 3002, 3003].indexOf(record.formType) > -1) && record.edit
                && [8001, 8002, 8003, 2101].indexOf(record.formType) === -1
                && (record.visibleLoanTypeScope !== 1004) && (record.visibleLoanTypeScope !== 1005) && (
                  <span>
                    <Popconfirm title={messages('request-2.key380')/*确认复制吗？*/} onConfirm={() => this.copyForm(record)}>
                      <a onClick={(e) => {e.stopPropagation()}}>{messages('common.copy')/*复制*/}</a>
                    </Popconfirm>
                    <Divider type="vertical"/>
                  </span>
                )}
                {record.edit && (
                  <span>
                    <a onClick={(e) => this.handleGoWorkflow(e, record)}>{messages('request-2.key381')/*配置审批流*/}</a>
                  </span>
                )}
              </div>
            )
          }
        }
      ],
      creatableList: [] //可创建的表单
    };
    this.formDetail = menuRoute.getRouteItem('form-detail','key'); //表单详情页
    this.workflow = menuRoute.getRouteItem('workflow','key'); //审批流列表页
  }

  handleGoWorkflow = (e, record) => {
    e.stopPropagation();
    let url = this.workflow.url.replace(':defaultFormOID', record.formOID);
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  copyForm = (record) => {
    formService.copyForm(record.formOID).then(res => {
      message.success(messages('request-2.key382')/*复制成功*/);
      this.simpleTableRef.getList(true);
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  handleMenuClick = (e) => {
    let redirect_url = menuRoute.getRouteItem('new-form').url.replace(':formType', e.key);
    this.context.router.push(redirect_url);
  };

  handleRowClick = (record) => {
    openSlideFrame.openFormSetting({
      formOID: record.formOID
    }, {
      afterClose: value => {
        typeof value === 'boolean' && value && this.simpleTableRef.getList(true);
      }
    }, this);
  };

  service = (page, pageSize, searchParams) => {
    const { selectedItem } = this.props;
    searchParams.entityType = selectedItem.type;
    return formService.getFormListV2(page, pageSize, searchParams);
  };

  expandedRowRender= (record) => {
    return record.referenceOID ? (
        <div>
          {[3001, 3002, 3003].indexOf(record.formType) > -1 && (
            <span>
              {messages('request-2.key383')/*关联申请单：*/}
            </span>
          )}
          {[2001, 2002].indexOf(record.formType) > -1 && (
            <span>
              {messages('request-2.key384')/*关联报销单：*/}
            </span>
          )}
          <a onClick={() => this.toGoReferenceDetail(record.referenceOID)}>
            {record.referenceFormName}&nbsp;
            {record.referenceFormCode && `(${record.referenceFormCode})`}
          </a>
        </div>
      ) : null
  };

  toGoReferenceDetail = (referenceOID) => {
    let url = this.formDetail.url.replace(':formOID', referenceOID);
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  componentDidMount(){
    const { selectedItem } = this.props;
    formService.getCreatableList(selectedItem.id).then(res => {
      if (res.data && res.data.length) {
        this.setState({creatableList: res.data});
      }
    }).catch(e => {
      errorMessage(e.response);
    });
  }

  render() {
    const { searchForm, columns, creatableList } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {creatableList.map(item => <Menu.Item key={item.code}>{item.value}</Menu.Item>)}
      </Menu>
    );
    {/*tableName已使用过：'form-list'*/}
    return (
      <div className="full-height-page">
        <AdvancedTable
          title={messages('request-2.key385')/*表单设置*/}
          columns={columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="formOID"
          expandedRowRender={record => this.expandedRowRender(record)}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          onRef={ref => this.simpleTableRef = ref}
          tableScrollMinHeight={ 1000 }
          tableName='form-list-v2'
          expandAll
        >
          <div className="table-header-buttons" style={{position: 'relative'}}>
            <Space>
              {creatableList && !!creatableList.length && (
                <Dropdown overlay={menu}>
                  <Button type="primary">
                    {messages('common.create')/*新建*/} <Icon type="down"/>
                  </Button>
                </Dropdown>
              )}
            </Space>
          </div>
        </AdvancedTable>
      </div>
    )
  }
}

FormListV2.PropTypes = {
  selectedItem: React.PropTypes.any,
};

FormListV2.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(FormListV2);
